package com.googlecode.spreadit.receiver;

import java.util.Arrays;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;

import com.googlecode.spreadit.bean.Message;
import com.googlecode.spreadit.bean.SpreadChannel;
import com.googlecode.spreadit.handler.SpreadRuleHandler;

/**
 * Handler for incoming SMS to extract content and pass the information to the
 * {@link SpreadRuleHandler}.
 * 
 * @author Markus L. Dechert (markus.dechert@googlemail.com)
 */
public class SmsReceiver extends BroadcastReceiver {

	private final String LOG_TAG = getClass().getSimpleName();

	/**
	 * Core method of this class: extracts the information from the SMS and
	 * calls the {@link SpreadRuleHandler} for finding a match and (if so)
	 * spreading the message accordingly.
	 */
	@Override
	public void onReceive(Context context, Intent intent) {
		Log.d(LOG_TAG, "SmsReceiver called.");

		// Extract message elements from SMS
		final List<SmsMessage> msgs = getMessagesFromIntent(intent);
		final String msgSubject = getMessageSubject(msgs);
		final String msgBody = getMessageBody(msgs);
		final String msgSender = getMessageSender(msgs);

		final Message m = new Message(msgSubject, msgBody, msgSender,
				SpreadChannel.SMS);

		Log.d(LOG_TAG, "Extracted sender [" + m.getSender() + "], subject ["
				+ m.getSubject() + "], body [" + m.getBody() + "]");

		final SpreadRuleHandler srh = SpreadRuleHandler.getInstance();
		srh.matchAndSpread(context, m);
	}

	private List<SmsMessage> getMessagesFromIntent(Intent intent) {

		try {
			Bundle bundle = intent.getExtras();
			Object pdus[] = (Object[]) bundle.get("pdus");
			SmsMessage[] msgs = new SmsMessage[pdus.length];
			for (int i = 0; i < pdus.length; i++) {
				final byte[] byteData = (byte[]) pdus[i];
				msgs[i] = SmsMessage.createFromPdu(byteData);
			}
			return Arrays.asList(msgs);

		} catch (Exception e) {
			Log.e("GetMessages", "fail", e);
			return null;
		}
	}

	private String getMessageSubject(List<SmsMessage> msgs) {
		StringBuilder s = new StringBuilder();
		for (SmsMessage m : msgs) {
			s.append(m.getPseudoSubject());
		}
		return s.toString().trim();
	}

	private String getMessageBody(List<SmsMessage> msgs) {
		StringBuilder s = new StringBuilder();
		for (SmsMessage m : msgs) {
			s.append(m.getDisplayMessageBody());
		}
		return s.toString().trim();
	}

	private String getMessageSender(List<SmsMessage> msgs) {
		String result = "";
		if (msgs != null && msgs.get(0) != null) {
			result = msgs.get(0).getOriginatingAddress();
		}
		result = (result != null) ? result.trim() : "";
		return result;
	}
}
